//
//  TTEmoticonView.swift
//  TTWeibo
//
//  Created by 陶宏路 on 16/7/29.
//  Copyright © 2016年 陶路路. All rights reserved.
//

import UIKit

class TTEmoticonView: UIView {

    override init(frame: CGRect) {
        
        super.init(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 216))
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI(){
        
        addSubview(emotionTooBar)
        
        addSubview(emoticoncollection)
        
        
        emotionTooBar.snp_makeConstraints { (make) -> Void in
            
            make.bottom.leading.trailing.equalTo(self)
            make.height.equalTo(37)
        }
        emoticoncollection.snp_makeConstraints { (make) -> Void in
            
            make.top.leading.trailing.equalTo(self)
            make.bottom.equalTo(emotionTooBar.snp_top)
        }
        
        emotionTooBar.closeBlock = {(type:TTEmotionTooBarType) in
            
            self.emoticoncollection.scrollToItemAtIndexPath(NSIndexPath(forRow: 0, inSection: type.rawValue), atScrollPosition: UICollectionViewScrollPosition.None, animated: false)
        }
        
    }
    
    private lazy var emotionTooBar:TTEmotionTooBar = TTEmotionTooBar(frame: CGRectZero)
    
    private lazy var emoticoncollection :TTEmoticoncollection = {
        let collec = TTEmoticoncollection()
        collec.pagingEnabled = true
        collec.showsHorizontalScrollIndicator = false
        collec.showsVerticalScrollIndicator = false
        collec.bounces = false
        collec.delegate = self
        return collec
    }()
}

// collectionView button 联动

extension TTEmoticonView:UICollectionViewDelegate{
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        let centerLine = scrollView.contentOffset.x + SCREENW * 0.5
        
        let cell = self.emoticoncollection.visibleCells().sort { (cell1, cell2) -> Bool in
            
            return cell1.frame.origin.x < cell2.frame.origin.x
        }
        
        if cell.count == 2{
            
            let fristCell = cell.first
            let lastCell = cell.last
            let indexPath:NSIndexPath?
            if fristCell!.frame.contains(CGPoint(x: centerLine, y: 0)){
                
                indexPath = self.emoticoncollection.indexPathForCell(fristCell!)
            }else{
                indexPath = self.emoticoncollection.indexPathForCell(lastCell!)
            }
            
            emotionTooBar.setCurrentSender((indexPath?.section)!)
        }
        
    }
}
